package com.lzy.conf;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.http.HttpHeaders;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String header = request.getHeader("Authorization");
        if (header == null || !header.startsWith("lzy ")) {
            return;
        }
        if("post".equalsIgnoreCase(template.method()) && template.body() == null){
            //如果是表单方式要设置 application/x-www-form-urlencoded
            String queryLine = template.queryLine();
            template.queries(new HashMap<>());
            if(StringUtils.hasText(queryLine) && queryLine.startsWith("?")){
                template.body(queryLine.substring(1));
                template.header(HttpHeaders.CONTENT_TYPE,"application/x-www-form-urlencoded");
            }
        }
        template.header(HttpHeaders.AUTHORIZATION, request.getHeader("Authorization"));
    }

}
